package com.sjyl.kaoshitong.util;

import org.apache.http.impl.auth.UnsupportedDigestAlgorithmException;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by ChangerLow on 14-4-11.
 */
public class MD5Helper {
    private static String TAG="MD5";
    private static char sHexDigits[] = { '0', '1', '2', '3', '4', '5', '6',
            '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
    private static MessageDigest sDigest;

    public MD5Helper(){

    }

    public static String hexString(byte[] source) {
        if (source == null || source.length <= 0) {
            return "";
        }

        final int size = source.length;
        final char str[] = new char[size * 2];
        int index = 0;
        byte b;
        for (int i = 0; i < size; i++) {
            b = source[i];
            str[index++] = sHexDigits[b >>> 4 & 0xf];
            str[index++] = sHexDigits[b & 0xf];
        }
        return new String(str);
    }


    static {
        try {
            sDigest = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            android.util.Log.e(TAG, "Get MD5 Digest failed.");
            throw new UnsupportedDigestAlgorithmException("MD5", e);
        }
    }



    final public static String encodeMD5(String source) {
        byte[] btyes = source.getBytes();
        byte[] encodedBytes = sDigest.digest(btyes);

        return hexString(encodedBytes);
    }
}
